package cn.source.system.config;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.source.common.utils.spring.SpringUtils;
import cn.source.system.domain.DbConn;
import cn.source.system.domain.DbMailConfig;
import cn.source.system.service.IDbMailConfigService;
import cn.source.system.utils.SpringFactoryUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
@Slf4j
public class MailConfig {

    public static final String MAIL_CONFIG_BEAN_NAME = "dbMailConfig";

    @Autowired
    private IDbMailConfigService mailConfigService;

    @PostConstruct
    public void init() {
        log.info("初始化邮件配置");
        List<DbMailConfig> dbMailConfigs = mailConfigService.selectDbMailConfigList(new DbMailConfig());
        if (dbMailConfigs.size() > 0) {
            registerMailConfig(dbMailConfigs.get(0));
        }
    }

    public static void registerMailConfig(DbMailConfig dbMailConfig) {
        // 创建MailAccount对象
        MailAccount account = new MailAccount();
        // 设置邮件服务器主机名
        account.setHost(dbMailConfig.getHost());
        // 设置邮件服务器端口号
        account.setPort(dbMailConfig.getPort().intValue());
        // 设置发件人邮箱用户名
        account.setUser(dbMailConfig.getUser());
        // 设置发件人邮箱密码或授权码
        account.setPass(dbMailConfig.getPass());
        // 设置发件人邮箱地址
        account.setFrom(dbMailConfig.getFrom());
        // 设置是否使用SSL加密连接
        account.setSslEnable(dbMailConfig.getSsl().equals("1"));

        //加入到spring环境中
        SpringFactoryUtil.registerBean(MAIL_CONFIG_BEAN_NAME, account);
    }

    public static void sedMail(String to, String title, String content) {
        MailAccount account = (MailAccount) SpringUtils.getBean(MAIL_CONFIG_BEAN_NAME);
        MailUtil.send(account, to, title, content, false);
    }


}
